<template>
  <div class="search-suggestion">
    <van-cell
      icon="search"
      v-for="(str, index) in suggestions"
      :key="index"
      @click="$emit('search', str)"
    >
      <div slot="title" v-html="highlight(str)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search'
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  components: {},

  props: {
    searchText: {
      type: String,
      required: true
    }
  },

  data () {
    return {
      // 联系建议参数列表
      suggestions: []
    }
  },

  computed: {},

  watch: {
    searchText: {
      // 当数据发生变化会执行 handler 处理函数
      // 防抖
      handler: debounce(async function () {
        const { data } = await getSearchSuggestions(this.searchText)
        this.suggestions = data.data.options
      }, 1000),
      // async handler () {
      //   // 找到数据接口
      //   // 请求获取数据
      //   // 模板绑定展示
      //   const { data } = await getSearchSuggestions(this.searchText)
      //   this.suggestions = data.data.options
      //   // console.log(data)
      // },
      // 该回调会在侦听开始之后立即调用
      immediate: true
    }
  },

  created () {},

  mounted () {},

  methods: {
    highlight (str) {
      return str.replace(
        new RegExp(this.searchText, 'gi'),
        `<span style="color: red">${this.searchText}</span>`
      )
    }
  }
}

</script>
<style lang='less' scoped>
</style>
